import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface LanguageOption {
  label: string
  value: string
}

// 定义系统支持的语言
export const SUPPORTED_LANGUAGES: LanguageOption[] = [
  { value: 'Java', label: 'Java' },
  // { value: 'Go', label: 'Golang' },
  // { value: 'C++', label: 'C++' },
  // { value: 'Python', label: 'Python3' },
];

const LOCAL_STORAGE_KEY = 'sakura-editor-language'

export const useEditorStore = defineStore('editor', () => {
  // 从本地存储读取初始语言，默认为 Java
  const getInitialLang = (): string => {
    try {
      const savedLang = localStorage.getItem(LOCAL_STORAGE_KEY)
      return savedLang ? savedLang : 'Java'
    } catch (e) {
      return 'Java'
    }
  }

  const selectedLanguage = ref<string>(getInitialLang())
  const supportedLanguages = ref<LanguageOption[]>(SUPPORTED_LANGUAGES)

  const setSelectedLanguage = (lang: string) => {
    selectedLanguage.value = lang
    try {
      localStorage.setItem(LOCAL_STORAGE_KEY, lang)
    } catch (e) {
      console.error('Failed to save language preference to localStorage', e)
    }
  }

  // 提供一个计算属性，返回当前选中语言对应的标签
  const selectedLanguageLabel = computed(() => {
    return supportedLanguages.value.find(lang => lang.value === selectedLanguage.value)?.label || selectedLanguage.value;
  })

  return {
    selectedLanguage,
    supportedLanguages,
    setSelectedLanguage,
    selectedLanguageLabel
  }
}) 